const fs = require('fs')
const path = require('path')
const jwt = require("jsonwebtoken");

module.exports = {
    //生成token
    generateToken(account) {
        let created = Math.floor(Date.now() / 1000);
        let cert = fs.readFileSync(path.join(__dirname, '../pem/rsa_private_key.pem'));//私钥 
        return jwt.sign({
            account,
            exp: created + 60 * 1440,
            iat: created,
        }, cert, { algorithm: 'RS256' });
    },

    // 校验token
    verifyToken(token) {
        let cert = fs.readFileSync(path.join(__dirname, '../pem/rsa_public_key.crt'));//公钥 
        let res;
        try {
            let result = jwt.verify(token, cert, { algorithms: ['RS256'] }) || {};
            let current = Math.floor(Date.now() / 1000);
            let { exp = 0 } = result
            if (current <= exp) {
                res = result.data || {};
            }
        } catch (e) {
            res = 'err';
        }
        return res;
    },
    // 重新token
    refreshToken(account) {
        let created = Math.floor(Date.now() / 1000);
        let cert = fs.readFileSync(path.join(__dirname, '../pem/rsa_private_key.pem'));//私钥 
        let token = jwt.sign({
            account,
            exp: created + 60 * 30, // 过期时间 
            iat: created, // 创建时间
        }, cert, { algorithm: 'RS256' });
        return token;
    }
}

